const mysql = require('mysql2/promise')
const bcrypt = require('bcrypt')

const dbConfig = {
  host: 'localhost',
  user: 'root',
  password: 'GKL9512357',
  database: 'novel_platform',
  charset: 'utf8mb4'
}

async function createAdminUser () {
  let connection
  try {
    connection = await mysql.createConnection(dbConfig)

    const adminEmail = 'admin@test.com'
    const adminPassword = 'admin123'
    const adminUsername = 'admin'
    const adminNickname = '管理员'

    console.log('🔍 检查管理员用户是否已存在...')

    // 检查用户是否已存在
    const [existingUsers] = await connection.execute(
      'SELECT id FROM users WHERE email = ? OR username = ?',
      [adminEmail, adminUsername]
    )

    if (existingUsers.length > 0) {
      console.log('⚠️ 管理员用户已存在，删除后重新创建...')
      await connection.execute(
        'DELETE FROM users WHERE email = ? OR username = ?',
        [adminEmail, adminUsername]
      )
    }

    console.log('🔐 加密密码...')
    const saltRounds = 10
    const passwordHash = await bcrypt.hash(adminPassword, saltRounds)

    console.log('👤 创建管理员用户...')
    const [result] = await connection.execute(
      `INSERT INTO users (username, email, nickname, password_hash, role, status, level, coins, is_vip, created_at, updated_at) 
       VALUES (?, ?, ?, ?, 'admin', 'active', 10, 10000, true, NOW(), NOW())`,
      [adminUsername, adminEmail, adminNickname, passwordHash]
    )

    console.log('✅ 管理员用户创建成功！')
    console.log(`📧 邮箱: ${adminEmail}`)
    console.log(`🔑 密码: ${adminPassword}`)
    console.log(`👤 用户名: ${adminUsername}`)
    console.log(`🛡️ 角色: admin`)
    console.log(`🆔 用户ID: ${result.insertId}`)

    // 同时创建或更新普通用户的密码
    console.log('\n🔄 更新现有用户密码...')

    // 更新tudou用户的密码
    const tudouPassword = 'tudou123'
    const tudouPasswordHash = await bcrypt.hash(tudouPassword, saltRounds)

    await connection.execute(
      'UPDATE users SET password_hash = ? WHERE email = ?',
      [tudouPasswordHash, 'tudou@example.com']
    )

    console.log(`✅ 更新用户密码成功:`)
    console.log(`📧 邮箱: tudou@example.com`)
    console.log(`🔑 密码: ${tudouPassword}`)
  } catch (error) {
    console.error('❌ 错误:', error.message)
  } finally {
    if (connection) await connection.end()
  }
}

createAdminUser()
